package FX;

import BasicClass.User;
import Connection.AccountDaoImpl;
import Connection.MyConnection;
import DAO.DaoException;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.util.Random;

public class Login extends Application {
    static boolean FirstLogin = true;//初始登录判断
    static int _Image_MAX_NUMBER_ = 10;//随机加载的最大图片数
    static MyConnection Myconnection = null;//数据库连接
    public static String Account_suc = "";//数据库搜索的正确登陆账号
    public static String Password_suc = "";//数据库搜索的正确登陆密码
    private final TextField account = new TextField();//键入账号控件--用于为全局变量传递数据
    private final PasswordField passwordField = new PasswordField();//键入密码控件--用于为全局变量传递数据
    @Override
    public void start(Stage primaryStage){
        Myconnection = new MyConnection("root","root");//默认连接数据库账户密码
        ManagerUI managerUI = new ManagerUI();//主界面声明
        User CurUser = new User("","");//用户声明
        //主窗口布局
        VBox rootNode = new VBox();
        Scene scene = new Scene(rootNode, 400, 270);
        Random random = new Random();
        String BackIMG = "./fodder/"+ random.nextInt(_Image_MAX_NUMBER_) +".jpg";
        //上端图片
        Image Blue_bg = new Image(BackIMG);
        ImageView imageview = new ImageView(Blue_bg);
        imageview.setFitHeight(100);

        //账号
        Label account_lab = new Label("账号");
        HBox hb_account = new HBox();
        hb_account.getChildren().addAll(account_lab, account);
        hb_account.setAlignment(Pos.CENTER);
        hb_account.setSpacing(10);
        hb_account.setPadding(new Insets(10, 10, 10, 10));
        //密码
        Label pass_lab = new Label("密码");
        HBox hb_pass = new HBox();
        hb_pass.getChildren().addAll(pass_lab, passwordField);
        hb_pass.setAlignment(Pos.CENTER);
        hb_pass.setSpacing(10);
        hb_pass.setPadding(new Insets(10));

        //登录按钮
        HBox hBox_log = new HBox();
        Button login = new Button("登录");
        login.setStyle("-fx-background-color: RGB(0, 237, 255);");
        login.setPrefSize(150, 30);
        hBox_log.getChildren().add(login);
        hBox_log.setAlignment(Pos.CENTER);

        //底部词条
        AnchorPane anchorPane = new AnchorPane();
        Hyperlink hyperlink = new Hyperlink("联系管理员");
        Label judge = new Label();
        Image image_KS = new Image("./fodder/二维码.png");
        ImageView imageView_KS = new ImageView(image_KS);
        imageView_KS.setFitHeight(30);
        imageView_KS.setPreserveRatio(true);
        anchorPane.getChildren().addAll(hyperlink, judge, imageView_KS);
        AnchorPane.setLeftAnchor(hyperlink, 3.0);
        AnchorPane.setTopAnchor(login, 3.0);
        AnchorPane.setRightAnchor(imageView_KS, 3.0);
        AnchorPane.setBottomAnchor(judge, 3.0);
        AnchorPane.setLeftAnchor(judge, (scene.getWidth() - 50) / 2);

        //主布局
        rootNode.getChildren().addAll(imageview, hb_account, hb_pass, hBox_log, anchorPane);

        //弹出对话框
        hyperlink.setOnMouseClicked(event -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Information");
            alert.setHeaderText("管理员:q2576583024");
            alert.setContentText("账号注册/密码重置");
            alert.initStyle(StageStyle.UTILITY);//不显示图标
            alert.show();
        });
        //键盘响应回车登录
        account.setOnKeyPressed(e -> {
            UserTransmit(account, CurUser);
            if (e.getCode() == KeyCode.ENTER) {
                login_judge(managerUI, account, passwordField, judge, primaryStage, CurUser);
            }
        });
        passwordField.setOnKeyPressed(e -> {
            UserTransmit(account, CurUser);
            if (e.getCode() == KeyCode.ENTER) {
                login_judge(managerUI, account, passwordField, judge, primaryStage, CurUser);
            }
        });
        //按钮点击进行登录
        login.setOnAction(e -> {
            UserTransmit(account, CurUser);
            login_judge(managerUI, account, passwordField, judge, primaryStage, CurUser);
        });

        primaryStage.setTitle("登录窗口");
        primaryStage.getIcons().add(new Image("fodder/查看书籍.png"));
        primaryStage.setResizable(false);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    public void login_judge(ManagerUI managerUI, TextField account, PasswordField password,
                            Label text, Stage stage, User user) {
        ManagerUI.setUser(user);//传递当前用户
        ManagerUI.setMyConnection(Myconnection);//传递数据库连接
        if (account.getText().trim().equals(Account_suc)
                & password.getText().trim().equals(Password_suc)) {//登录成功判断
            if (isFirstLogin())managerUI.start(new Stage());//初始登录传递数据，声明变量
            else {
                ManagerUI.updateUser(user);
                ManagerUI.UpdateWindows(ManagerUI.rootNode);
                ManagerUI.getManagerStage().show();
            }
            ManagerUI.setLogin(stage);
            stage.hide();
        } else if (account.getText().trim().equals("")) {
            text.setText("账号为空");
        } else if (Account_suc.equals("账号不存在")) {
            text.setText("无该账号");
        } else {
            text.setText("密码错误");
        }
    }

    static void UserTransmit(TextField account, User CurUser){
        /*用户转换函数
        * 将键入账户控件的账户进行数据库查询
        * 返回 查询到的账户密码
        * */
        CurUser.setNumber(account.getText());
        AccountDaoImpl accountDaoImpl = new AccountDaoImpl(Myconnection);
        try{
            accountDaoImpl.getAccount(CurUser);
            Account_suc = CurUser.getNumber();
            Password_suc = CurUser.getPassword();
        } catch (DaoException e) {
            e.printStackTrace();
        }
    }
    public static boolean isFirstLogin() {return FirstLogin;}
    public static void setFirstLogin(boolean firstLogin) {FirstLogin = firstLogin;}
}
